package client.gui;
import java.awt.*;

import javax.swing.*;
import java.awt.event.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;
import sharedspace.*;
import java.sql.*;


import messages.MessageExtraTimeCheck;
import messages.MessageExtraTimeCheckReply;
import messages.MessageExtraTimeCheckReply.ErrMsg;
import messages.MessageStudentInTest;
import messages.MessageStartTime;
import messages.MessageSumbitTestChoices;

/**
 * this class show the computerized test
 * @author Amir S.
 * @author Jacob C.
 * @author Maya G.
 * @author Michael V.
 *
 */
public class GUI_ComputerizeTest extends JPanel{
	
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<QuestionInTest> questionInTestList;
	private StudentInTest studentInTest;
	private Course course;
	private List<Choices> choicesList;
	private JLabel headTitle;
	private JLabel question;
	private JLabel clock;
	private JLabel testDuration;
	private JRadioButton answer;
	private JLabel idLabel;
	private JTextField idTextField;
	private JButton startTestButton;
	private JButton submitTestButton;
	private JPanel form;
	private Client_GUI ms;
	private JScrollPane scroller = null;
	private GUI_ImagePanel background;
	
	/**
	 * 
	 * @param ms 
	 * @param questionInTestList
	 * @param course
	 */
	public GUI_ComputerizeTest(Client_GUI ms,List<QuestionInTest> questionInTestList,Course course)
	{
		super();
		this.questionInTestList = questionInTestList;
		this.course = course;
		this.choicesList = new ArrayList<Choices>();
		this.ms = ms;
		//this.ms.setResizable(true);
		initilized();
	}
	/**
	 * initilize screen
	 */
	public void initilized()
	{
		/*---------------------------------Initialize-Screen---------------------------------------------*/
		background = new GUI_ImagePanel(new ImageIcon("images/background1.jpg").getImage());
		background.setSize(new Dimension(1000, 700));
		
		add(background);
		
		headTitle = new JLabel("Computerized Test");
		headTitle.setFont(new Font("Arial", Font.PLAIN, 16));
		headTitle.setBounds(new Rectangle(273, 76, 412, 30));
		headTitle.setForeground(Color.BLUE);
		
		idLabel = new JLabel("Type your ID number:");
		idLabel.setFont(new Font("Arial", Font.PLAIN, 16));
		idLabel.setBounds(new Rectangle(269, 164, 67, 30));
		idLabel.setForeground(Color.BLUE);
		
		clock = new JLabel();
		clock.setFont(new Font("Arial", Font.PLAIN, 16));
		clock.setBounds(new Rectangle(10, 36, 171, 30));
		clock.setForeground(Color.BLUE);
		
		testDuration = new JLabel();
		testDuration.setFont(new Font("Arial", Font.PLAIN, 16));
		testDuration.setBounds(new Rectangle(10, 11, 171, 30));
		testDuration.setForeground(Color.BLUE);
		
		idTextField = new JTextField();
		idTextField.setLocation(new Point(100,100));
		idTextField.setFont(new Font("Arial", Font.PLAIN,16));
		idTextField.setBounds(new Rectangle(346, 165, 146, 30));
		
		startTestButton = new JButton();
		startTestButton.setFont(new Font("Arial", Font.BOLD | Font.PLAIN, 16));
		startTestButton.setBounds(new Rectangle(346, 205, 146, 34));
		startTestButton.setText("Start Test");
		/**
		 * action listener to start test 
		 */
		startTestButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				if(idTextField.getText().equals(ms.stdnt.getStudent().getUserID()))//student type ID
					{
						/*display Test*/
						displayTest();
						background.add(scroller);	
						background.add(submitTestButton);
						testDuration.setText("Test duration: "+Integer.toString(ms.stdnt.getExecuteTest().getTest().getTestDuration())+" minutes");
						background.add(testDuration);
						setStuedntInTest();
						startTimer();
						automaticCloser();
					
					}
				else JOptionPane.showMessageDialog(null,"Wrong ID");
				}
		}
		);
		
		submitTestButton = new JButton();
		submitTestButton.setFont(new Font("Arial", Font.BOLD | Font.PLAIN, 16));
		submitTestButton.setBounds(new Rectangle(805, 601, 146, 34));
		submitTestButton.setText("Sumbit Test");
		/**
		 * action lisitener to send test
		 */
		submitTestButton.addActionListener(new java.awt.event.ActionListener(){
			public void actionPerformed(java.awt.event.ActionEvent e) {
				int i = JOptionPane.showConfirmDialog(null, "Are you sure you finished the test?", "Submit Test", JOptionPane.YES_NO_OPTION);
				if (i==JOptionPane.YES_OPTION)
				{
					/*student send the test*/
					String endTime = DateUtils.now(DateUtils.dateFormat);
					String teacherID = ms.stdnt.getExecuteTest().getExecuter().getUserID();
					MessageSumbitTestChoices MsgStc = new MessageSumbitTestChoices(teacherID,choicesList,endTime);
					try 
					{
						ms.setContentPane(ms.stdnt);
						ms.client.sendToServer(MsgStc);
					}
					catch (IOException e1)
					{
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});
		
		
		this.setLayout(null);
		this.setSize(1000, 700);
		
		background.add(headTitle);
		background.add(idLabel);
		background.add(idTextField);
		background.add(startTestButton);
		//this.add(clock);
		//this.add(testDuration);
		
		
		
		
	}
	

	/**
	 *  display the test to student
	 */

	public void displayTest()
	{
		
		// set all student choices in test to -1 (if choice is -1 student didn't answer question) 
		for (int i = 0; i<questionInTestList.size(); i++)
		{
			Choices choice = new Choices();
			Question q = new Question();
			q.setQuestionID(questionInTestList.get(i).getQuestion().getQuestionID());
			choice.setQuestion(q);
			choice.setExecuteTestID(ms.stdnt.getExecuteTest().getExecuteTestID());
			choice.setStudentID(idTextField.getText());
			choice.setChoice(-1);
			choicesList.add(choice);
		}
		
		
		
		form = new JPanel(new VerticalLayout(50,VerticalLayout.LEFT));
		question = new JLabel("Test build by: "+questionInTestList.get(0).getTest().getAuthor().getUserFirstName()+ " "+ questionInTestList.get(0).getTest().getAuthor().getUserLastName());
		question.setFont(new Font("Arial",Font.PLAIN,16));
		question.setForeground(Color.BLACK);
		form.add(question);
		form.setBackground(Color.WHITE);
		idLabel.setVisible(false);
		idTextField.setVisible(false);
		startTestButton.setVisible(false);
		headTitle.setText("Test in "+ course.getCourseName() + " - Good Luck :-)");
		for( int i = 0; i<questionInTestList.size(); i++)//insert question to JPanel
		{
			JPanel qPanel = new JPanel(new VerticalLayout(0, VerticalLayout.LEFT)); 
			qPanel.setBackground(Color.WHITE);
			question = new JLabel("   "+(i+1)+". "+questionInTestList.get(i).getQuestion().getQuestion()+" ("+questionInTestList.get(i).getPointQuestion()+" points)");
			question.setFont(new Font("Arial",Font.PLAIN,16));
			question.setForeground(Color.BLACK);
			ButtonGroup buttonGroup = new ButtonGroup();
			qPanel.add(question);// insert question to question JPanel
			question = new JLabel("   "+questionInTestList.get(i).getQuestion().getQuestionCommet());
			qPanel.add(question);// insert questionComment to question JPanel
			for (int j = 0; j<4; j++)
			{   //making JRadioButton for answers
				answer = new JRadioButton((j+1)+". "+questionInTestList.get(i).getQuestion().getAnswers()[j]);
				answer.setActionCommand(Integer.toString(i));
				//Action Listener for JRadioButton
				answer.addActionListener(new ActionListener(){
					 public void actionPerformed(ActionEvent e) {
						 JRadioButton jr = (JRadioButton)e.getSource();
						 String string = jr.getText();
						 string = string.substring(0, 1);
						 int choice = Integer.parseInt(string);
						 string = jr.getActionCommand();
						 int question = Integer.parseInt(string);
						 choicesList.get(question).setChoice(choice);
						
					 }
				});
				answer.setBackground(Color.WHITE);
				qPanel.add(answer);
				buttonGroup.add(answer);
				
			}
			form.add(qPanel);
						
		}
		
		//form.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1,true));
		scroller = new JScrollPane(form);
		scroller.setBounds(50, 110, 800, 480);
		scroller.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2, true));
		
		
	}
	
	/**
	 * update StudentInTest and send it to database;
	 */
	public void setStuedntInTest()
	{
		studentInTest = new StudentInTest();
		Timestamp time;
		
		/*------------------------------Taking-Time-stamp-------------------------------------------------*/
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String startTime = DateUtils.now("yyyy-MM-dd HH:mm:ss");
		java.util.Date parseDate;
		
		try {
			parseDate = dateFormat.parse(startTime);
			time = new Timestamp(parseDate.getTime());
			studentInTest.setStartTest(time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(startTime);
		
		/*------------------------Creating-StudentInTest-------------------------------------------------*/
		studentInTest.setExecuteTestID(ms.stdnt.getExecuteTest().getExecuteTestID());
		studentInTest.setStudent(ms.stdnt.getStudent());
		studentInTest.setStudentComputerGrade(-1);
		long t = studentInTest.getStartTest().getTime();
		long m = 60000;
		studentInTest.setEndTest(new Timestamp(t-m));
		studentInTest.setTestCheckedComplete(false);
		studentInTest.setWordTestCheckedPath(null);
		
		/*-----------------------Sending-StudentInTest--------------------------------------------------*/
		MessageStudentInTest msgsit = new MessageStudentInTest(studentInTest,ms.stdnt.getExecuteTest());
		try
		{
			ms.client.sendToServer(msgsit);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
	
	/**
	 * send message to server to start counting time
	 */
	public void startTimer()
	{
		
		MessageStartTime MsgSt = new MessageStartTime(choicesList.get(0).getExecuteTestID(),choicesList.get(0).getStudentID());
		try {
			ms.client.sendToServer(MsgSt);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
	/**
	 * start timer and check every minute if test was lock
	 * or extra time add or time is finish
	 */
	public void automaticCloser() 
	{
		
		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
		int flag =0;	
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				try {
					String now = DateUtils.now(DateUtils.hour+":"+DateUtils.minutes);
					clock.setText("Time : "+now);
					background.add(clock);
					MessageExtraTimeCheck MsgEtc = new MessageExtraTimeCheck(choicesList.get(0).getStudentID(), choicesList.get(0).getExecuteTestID());
					ms.client.sendToServer(MsgEtc);
					MessageExtraTimeCheckReply msgetr = (MessageExtraTimeCheckReply)ms.client.GetMessage();
					if (msgetr.getErrMsg() == ErrMsg.TIME_OVER)
					{
						/*save student choice and send to server*/
						JOptionPane.showMessageDialog(null,"Time is over!\n" +"Sending test for checking");
						String teacherID = ms.stdnt.getExecuteTest().getExecuter().getUserID();
						MessageSumbitTestChoices MsgStc = new MessageSumbitTestChoices(teacherID,choicesList,"");
						ms.setContentPane(ms.stdnt);
						ms.client.sendToServer(MsgStc);
						this.cancel();
					}
					if (msgetr.getErrMsg() == ErrMsg.STOP_BY_TEACHER)
					{	/*save student choice and send to server*/
						JOptionPane.showMessageDialog(null,"Test locked by teacher!\n" +"Sending test for checking");
						String teacherID = ms.stdnt.getExecuteTest().getExecuter().getUserID();
						MessageSumbitTestChoices MsgStc = new MessageSumbitTestChoices(teacherID,choicesList,"");
						ms.setContentPane(ms.stdnt);
						ms.client.sendToServer(MsgStc);
						this.cancel();
					}
					if (msgetr.getErrMsg() == ErrMsg.ADD_EXTRA_TIME)
					{	/*notify student extra time added*/
						if (flag == 0)
						{
							JOptionPane.showMessageDialog(null, msgetr.getExtraTime()+" minutes is added to the test");
							remove(testDuration);
							testDuration.setText("Test duration: "+Integer.toString(ms.stdnt.getExecuteTest().getTest().getTestDuration()+msgetr.getExtraTime())+" minutes");
							background.add(testDuration);
							repaint();
							flag = 1;
						}
							
					}
					

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		};
		
		timer.schedule(timerTask, 0, 60*1000);
	
	

	}	
}
